<?php
namespace Common\Model;

/**
 * VPlanStatsModel
 *
 * @version $Id$
 * @copyright 2007 - 2013 tcisv.com Ltd.
 * @author cfstory <cfstory@163.com>
 */
class VPlanStatsModel extends Model {
    protected $tableName = 't_plan_stats';
    protected $viewName  = 'v_plan_stats';
    protected $pk        = 'uid';

    /**
     * _parseOptions
     * 拦截_parseOptions主要是为了自动生成表名
     * 生成表名时必须用到的参数有day和uid,也就是where()的条件必须要有day和uid
     *
     * @param mixed $options
     * @return void
     */
    protected function _parseOptions($options = null) {
        if(!empty($this->options['where']['day']) || empty($this->trueTableName)) {
            $day = empty($this->options['where']['day']) ? null : $this->options['where']['day'];

            if(empty($day)) {
                throw new ThinkException('请确认是否有day');
            }

            $timestamp  = strtotime($day);
            $tableName  = 'd' . date('Ymd', $timestamp) . '.'. $this->viewName;
            $options    = array_merge($options, array('table' => $tableName));

            $this->trueTableName = $tableName;

            unset($options['where']['day']);    //表中无day字段，用day主要是定位到对应日期的表上
        }

        return parent::_parseOptions($options);
    }

    protected function _options_filter(&$options) {
        if(!$loginUser = C('RUN_LOGIN_USER')) {
            exit('NO LOGIN');
        }

        if(in_array($loginUser['type'], array(1, 2))) {
            $options['where']        = isset($options['where']) ? $options['where'] : array();
            $options['where']['uid'] = $loginUser['uid'];

            return true;
        }

        return true;
    }

}
